package com.wxyzz.satserver.likeenshrine.task;

import com.wxyzz.common.core.exception.CustmerException;
import com.wxyzz.satserver.article.service.ArticleService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class LikeTask {

    @Resource
    private ArticleService articleService;

    @Resource
    private RedissonClient redissonClient;

    @Async
    @Scheduled(cron = "0 0 1 * * ?")
    public void updateLikeNum () {
        RLock lock = redissonClient.getLock("update:likeNum");

        try {
            if (lock.tryLock(10, 0, TimeUnit.SECONDS)) {
                articleService.updateLikeNum();
            }
        } catch (InterruptedException e) {
            throw new CustmerException(500, e.getMessage());
        } finally {
            if (lock.isHeldByCurrentThread() && lock.isLocked()) {
                lock.unlock();
            }
        }
    }
}
